package com.orhon.smartcampus.modules.systemctl.mutation;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.systemctl.dao.OperationUserRelationDao;
import com.orhon.smartcampus.modules.systemctl.dao.OperationsDao;
import com.orhon.smartcampus.modules.systemctl.entity.OperationUserRelation;
import com.orhon.smartcampus.modules.systemctl.entity.Operations;
import com.orhon.smartcampus.modules.systemctl.gqlInputModel.GQLSchoolOperationUsersRelationInput;
import com.orhon.smartcampus.modules.systemctl.inputMapper.SchoolOperationUsersRelationInputMapper;
import com.orhon.smartcampus.modules.user.dao.UsersDao;
import com.orhon.smartcampus.modules.user.entity.Users;

import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;

@Component
public class AddUsersOperationMutation implements DataFetcher {

    @Autowired
    private OperationUserRelationDao operationUserRelationDao;

    @Autowired
    private OperationsDao operationsDao;

    @Autowired
    private UsersDao usersDao;

    public Object get(DataFetchingEnvironment environment) throws Exception {
        GQLSchoolOperationUsersRelationInput input = SchoolOperationUsersRelationInputMapper.MAPPER.mapInput(environment.getArgument("inputData"));

       
        ArrayList<OperationUserRelation> list = new ArrayList<OperationUserRelation>();
        List<Long> ids = input.getOperation_id();
        
        for (Long operation_id : ids) {
        	 OperationUserRelation operationUserRelation = new OperationUserRelation();
        	 operationUserRelation.setCreatedAt(new Date());
        	 if(input.getOperation_id() != null) {
                 operationUserRelation.setSystemctlOperationsByOperationId(operationsDao.get(Operations.class,operation_id));
             }
             if(input.getUser_id() != null) {
                 operationUserRelation.setUserUsersByUserId(usersDao.get(Users.class, input.getUser_id()));
             }
             try{
                 operationUserRelationDao.saveOrUpdate(operationUserRelation);
                 list.add(operationUserRelation);
             }
             catch (Exception e){
                 return Result.error(500,""+e);
             }
		} 
        return Result.ok().put("data", list);
    }
}

